package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.UserSound;
import com.tanhua.dubbo.api.mongo.PeachblossomApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Random;


/**
 * 桃色api impl
 *
 * @author 沈某
 * @date 2021/07/18 09:07:20
 */
@Service
public class PeachblossomApiImpl implements PeachblossomApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * @param userSound 用户的声音
     * @Author 沈某
     * @date 2021/07/17 11:07:33
     */
    @Override
    public void save(UserSound userSound) {

        userSound.setId(new ObjectId());
        userSound.setCreated(new Date().getTime());

        mongoTemplate.save(userSound);
    }

    /**
     * @param userId 通过用户ID排除查询自己
     * @return {@link UserSound }
     * @Author 沈某
     * @date 2021/07/17 11:07:41
     */
    @Override
    public UserSound queryPeachblossom(Long userId) {

        //添加排除条件
        Criteria criteria = new Criteria();
        criteria.norOperator(Criteria.where("userId").is(userId));

        Query query = new Query(criteria);
        List<UserSound> userSounds = mongoTemplate.find(query, UserSound.class);

        //返回一个随机的userSoundTime对象
        return userSounds.get(new Random().nextInt(userSounds.size()));

    }

    /**
     * @删除获取的音频
     * @param soundTime
     * @Author 沈某
     * @date 2021/07/17 11:07:41
     */
    @Override
    public void delete(UserSound soundTime) {
        //根据获取音频的ID删除
        Query query = new Query(Criteria.where("userId").is(soundTime.getUserId()));
        mongoTemplate.remove(query,UserSound.class);

    }
}
